package com.lagou.ipersistence.type;

import com.lagou.ipersistence.session.Configuration;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Yan Jiahong
 * Created on 2020/11/22
 */
public final class TypeHandlerRegistry {
    private final Map<Class<?>, Map<JdbcType, TypeHandler<?>>> typeHandlerMap = new ConcurrentHashMap<>();
    
    public TypeHandlerRegistry() {
        register(String.class, JdbcType.VARCHAR, new StringTypeHandler());
        register(String.class, null, new StringTypeHandler());
        register(Date.class, JdbcType.DATE, new DateTypeHandler());
        register(Date.class, null, new DateTypeHandler());
        register(Long.class, JdbcType.INT, new IntegerTypeHandler());
        register(Long.class, JdbcType.INT, new LongTypeHandler());
        register(Long.class, null, new LongTypeHandler());
    }
    
    public void register(Class<?> javaType, JdbcType jdbcType, TypeHandler<?> typeHandler) {
        if (javaType != null) {
            Map<JdbcType, TypeHandler<?>> map = typeHandlerMap.computeIfAbsent(javaType, k -> new HashMap<>());
            map.put(jdbcType, typeHandler);
        }
    }
    
    public boolean hasTypeHandler(Class<?> type) {
        return false;
    }
    
    public boolean hasTypeHandler(Class<?> javaType, JdbcType jdbcType) {
        Map<JdbcType, TypeHandler<?>> map = typeHandlerMap.get(javaType);
        if (map != null) {
            return map.get(jdbcType) != null;
        }
        return false;
    }
    
    public <T> TypeHandler<T> getTypeHandler(Class<?> javaType, JdbcType jdbcType) {
        Map<JdbcType, TypeHandler<?>> map = typeHandlerMap.get(javaType);
        if (map != null) {
            return (TypeHandler<T>) map.get(jdbcType);
        }
        return null;
    }
}
